import { Button, Modal, message, Spin, Row, Col } from 'antd';

const confirm = Modal.confirm;
import { WeaErrorPage, WeaTools, WeaInput, WeaDialog, WeaRightMenu, WeaAlertPage, WeaMind, WeaLocaleProvider } from 'ecCom';
import { inject, observer } from 'mobx-react';
import { toJS } from 'mobx';

const ButtonGroup = Button.Group;
import { WeaTableNew } from 'comsMobx';

const WeaTable = WeaTableNew.WeaTable;
import AddContacterModal from '../dialog/AddContacterModal';

const getLabel = WeaLocaleProvider.getLabel;
const { ua } = WeaTools;

@inject('customerCardStore')
@observer
class ContacterMap extends React.Component {
  constructor(props) {
    super(props);
    this._jm = null;
    this.state = {
    };
    this.isIE9 = ua.browser === 'IE' && parseInt(ua.version, 10) < 10;
  }
  componentDidMount() {
    const { customerCardStore, location: { query } } = this.props;
    customerCardStore.contacterMap.initDatas(query, () => {
      if (this._jm) { this.initMap(); }
    });
    window.saveDragendMind = this.saveContracterMind;
  }
    initMap = () => {
      const { customerCardStore: { contacterMap } } = this.props;
      const { mapDatas, canEdit } = contacterMap;

      if (this._jm) {
        this._jm._reset();
      } else {
        const options = {
          container: 'jsmind_container',
          editable: false,
          theme: 'weaver',
          support_html: true,
        };
        this._jm = new window.jsMind(options);
      }
      const mind = {
        meta: {},
        format: 'node_array',
        data: mapDatas.slice(0),
      };
      this._jm.show(mind);
      if (canEdit) {
        this.editable();
      }
    }

    saveContracterMind = (arr, old_parent, new_parent, selectd_node) => {
      this.editable();
      const { customerCardStore: { contacterMap } } = this.props;
      const { customerId, initDatas, saveContracterOperate } = contacterMap;
      if (old_parent && new_parent && old_parent !== new_parent) {
        saveContracterOperate({
          datas: JSON.stringify(arr),
          old_parent,
          new_parent,
          customerId,
          contacterId: selectd_node,
        }, this.initMap);
      }
    }

    jsmindLoading = (end) => {
      if (end) {
        this.initMap();
      }
    }

    render() {
      const { customerCardStore: { contacterMap } } = this.props;
      const { contacterNum, total_attitude, customerId, showMapLog, visible, loading, tableStore, verified, hasRight, operateObj } = contacterMap;
      if (verified && !hasRight) {
        return (<WeaAlertPage ecId={`${this && this.props && this.props.ecId || ''}_WeaAlertPage@v5qiid`} >
          <div style={{ color: '#000' }}>
            {getLabel(2012, '对不起，您暂时没有权限！')}
          </div>
        </WeaAlertPage>
        );
      }
      if (verified && hasRight) {
        return (
          <WeaRightMenu
            ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@cetxhh`}
            datas={this.getRightMenu()}
            onClick={this.onRightMenuClick.bind(this)}
            collectParams={{
              favname: getLabel(20323, '客户信息'),
              favouritetype: 4,
              importantlevel: 1,
              objid: -1,
            }}
          >
            <div style={{ height: '100%' }} className="crm-card-contacter-map">
              <div className="contacter-map-header">
                <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@o00lgs`}>
                  <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@2qav8i`} span={12}>{getLabel(18609, '共')}{contacterNum}{getLabel(27591, '个') + getLabel(572, '联系人')}：{total_attitude}</Col>
                  <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@ho6pb7`} span={12} className="button-right">
                    <ButtonGroup ecId={`${this && this.props && this.props.ecId || ''}_ButtonGroup@53syxe`} size="small">
                      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@lf2f87`} type="primary" onClick={this.expand_all}>{getLabel(84533, '展开全部')}</Button>
                      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@kw0lsu`} onClick={this.collapse_all}>{getLabel(84532, '收缩全部')}</Button>
                      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@rw15au`} type="primary" icon="plus" onClick={this.zoomIn}>{getLabel(22208, '放大')}</Button>
                      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@vph1v1`} icon="minus" onClick={this.zoomOut}>{getLabel(22209, '缩小')}</Button>
                      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@hhspii`} onClick={showMapLog}>{getLabel(83, '日志')}</Button>
                    </ButtonGroup>
                  </Col>
                </Row>
              </div>
              <div style={{ display: 'hidden' }}> <WeaMind ecId={`${this && this.props && this.props.ecId || ''}_WeaMind@de1pvf`} onCreate={this.jsmindLoading} /></div>
              <div className="contacter-map-content" id="jsmind_container" />
              <WeaDialog
                ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@gnn6zu`}
                style={{ width: 800, height: 520 }}
                visible={visible}
                title={getLabel(32061, '操作日志')}
                icon="icon-coms-crm"
                iconBgcolor="#96358a"
                buttons={[
                  <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@ykxrj7@close`} onClick={() => contacterMap.setVisible(false)}>{getLabel(309, '关闭')}</Button>,
                ]}
                onCancel={() => contacterMap.setVisible(false)}
              >
                <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@oiouzr`} datas={this.getDialogRightMenu()} >
                  <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@dj7foj`} spinning={loading}>
                    <WeaTable
                      ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@753li9`}
                      comsWeaTableStore={tableStore}
                      hasOrder
                      needScroll
                    />
                  </Spin>
                </WeaRightMenu>
              </WeaDialog>
              <AddContacterModal ecId={`${this && this.props && this.props.ecId || ''}_AddContacterModal@9nsdvj`} ref="operateContacterModal" customerId={customerId} contentStore={contacterMap} onSave={(params) => { contacterMap.saveContacter(params, this.initMap); }} type={operateObj.operation || 'add'} />
            </div>
          </WeaRightMenu>
        );
      }
      return <div />;
    }
    expand_all=() => {
      this._jm.expand_all();
    }
    collapse_all=() => {
      this._jm.collapse_all();
    }
    zoomIn=() => {
      if (this.isIE9) {
        Modal.info({
          title: getLabel(15172, '系统提示'),
          content: `${getLabel(127928, '您当前的浏览器是IE浏览器版本过低，请升级IE至')}10+`,
          okText: getLabel(33703, '确定'),
        });
      } else {
        this._jm.view.zoomIn();
      }
    }
    zoomOut=() => {
      if (this.isIE9) {
        Modal.info({
          title: getLabel(15172, '系统提示'),
          content: `${getLabel(127928, '您当前的浏览器是IE浏览器版本过低，请升级IE至')}10+`,
          okText: getLabel(33703, '确定'),
        });
      } else {
        this._jm.view.zoomOut();
      }
    }

    editable= () => {
      this._jm.enable_edit();
    }

    getDialogRightMenu = () => {
      const { customerCardStore: { contacterMap } } = this.props;
      const btns = [];
      btns.push({
        icon: <i className="icon-coms-Custom " />,
        content: getLabel(382660, '显示定制列'),
        key: '1',
        onClick: () => contacterMap.onShowColumn(),
      });
      return btns;
    }

    getRightMenu=() => {
      const { customerCardStore: { contacterMap } } = this.props;
      const { rightMenu } = contacterMap;
      const btns = [];
      rightMenu && rightMenu.length > 0 && rightMenu.map((m) => {
        btns.push({
          icon: <i className={m.menuIcon} />,
          content: m.menuName,
        });
      });
      return btns;
    }

    onRightMenuClick(key) {
      const { customerCardStore: { contacterMap } } = this.props;
      const { rightMenu, customerId } = contacterMap;
      const that = this;
      const node = this._jm.get_selected_node();
      rightMenu && rightMenu.length > 0 && rightMenu.map((m, i) => {
        	if (Number(key) == i) {
          if (m.type == 'BTN_REVOKE') {
            contacterMap.resetContacterMap({ customerId, action: 'reset' }, this.initMap);
          } else if (m.type == 'BTN_CREATE') {
            let parentid = 'root';
            let direction = '1';
            if (node !== null) {
              parentid = node.id;
              direction = node.direction;
            }
            contacterMap.addContacterForm({ operation: 'add', parentid, direction });
            this.refs.operateContacterModal.setVisible(true);
          } else if (m.type == 'BTN_EDIT') {
            if (node == null || node.id == 'root') {
              Modal.info({
                title: getLabel(15172, '系统提示'),
                content: getLabel(15612, '请选择目标节点！'),
                okText: getLabel(33703, '确定'),
              });
            } else {
              contacterMap.addContacterForm({ operation: 'edit', contacterId: node.id });
              this.refs.operateContacterModal.setVisible(true);
            }
          } else if (m.type == 'BTN_DELETE') {
            if (node == null || node.id == 'root') {
              Modal.info({
                title: getLabel(15172, '系统提示'),
                content: getLabel(15612, '请选择目标节点！'),
                okText: getLabel(33703, '确定'),
              });
            } else {
              contacterMap.deleteContacterMap({ customerId, contacterId: node.id, action: 'delete' }, this.initMap);
            }
          }
        }
      });
    }
}


export default WeaTools.tryCatch(React,
  props => <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@zi9cuf`} msg={props.error ? props.error : getLabel(129417, '服务器运行出错，请联系系统管理员！')} />,
  { error: '' },
)(ContacterMap);
